package com.shengqi.xinnongren.work.ui.goods.activities;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.shengqi.xinnongren.R;
import com.shengqi.xinnongren.common.base.BaseMvpActivity;
import com.shengqi.xinnongren.common.config.user.UserManager;
import com.shengqi.xinnongren.common.utils.ImageUtils;
import com.shengqi.xinnongren.common.utils.LogUtil;
import com.shengqi.xinnongren.common.utils.ToastHelper;
import com.shengqi.xinnongren.work.dialog.OrderCouponChooseDialog;
import com.shengqi.xinnongren.work.dialog.OrderTimeChooseDialog;
import com.shengqi.xinnongren.work.model.HttpRespond;
import com.shengqi.xinnongren.work.ui.goods.model.ConfirmOrderBean;
import com.shengqi.xinnongren.work.ui.goods.presenter.ConfirmOrderPresenter;
import com.shengqi.xinnongren.work.ui.goods.view.ConfirmOrderView;
import com.shengqi.xinnongren.work.ui.home.model.CartGoodsBean;
import com.shengqi.xinnongren.work.ui.user.activities.AddressActivity;
import com.shengqi.xinnongren.work.ui.user.model.AddressBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 结算--确认订单
 */
public class ConfirmOrderActivity extends BaseMvpActivity<ConfirmOrderView, ConfirmOrderPresenter> implements ConfirmOrderView, CompoundButton.OnCheckedChangeListener {

    private static final String EXTRA_TYPE = "type";
    private static final String EXTRA_MONEY = "money";
    private static final String EXTRA_CONTENT = "content";

    @BindView(R.id.tv_title_left)
    TextView mTvTitleLeft;
    @BindView(R.id.tv_title_right)
    TextView mTvTitleRight;
    @BindView(R.id.tv_address)
    TextView mTvAddress;
    @BindView(R.id.tv_date)
    TextView mTvDate;
    @BindView(R.id.tv_time)
    TextView mTvTime;

    @BindView(R.id.tv_store_name)
    TextView mTvStoreName;
    @BindView(R.id.tv_store_address)
    TextView mTvStoreAddress;
    @BindView(R.id.tv_store_tel)
    TextView mTvStoreTel;

    @BindView(R.id.tv_date2)
    TextView mTvDate2;
    @BindView(R.id.tv_time2)
    TextView mTvTime2;
    @BindView(R.id.tv_shopping_bag)
    TextView mTvShoppingBag;
    @BindView(R.id.tv_coupon)
    TextView mTvCoupon;
    @BindView(R.id.tv_integral)
    TextView mTvIntegral;

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.edt_remark)
    EditText mEdtRemark;

    @BindView(R.id.tv_goods_num)
    TextView mTvGoodsNum;    //件数
    @BindView(R.id.tv_total_money)
    TextView mTvTotalMoney;   //小计金额
    @BindView(R.id.tv_final_money)
    TextView mTvFinalMoney;  //预付款

    @BindView(R.id.tv_address_update)
    TextView mTvAddressUpdate; //修改
    @BindView(R.id.tv_no_address)
    TextView mTvNoAddress;

    @BindView(R.id.check_integral)
    CheckBox mCbIntegral;
    private String integralVal;


    private int type; //0  取货  1 送货上门
    private String money; //金额
    private List<CartGoodsBean> mList;

    private List<ConfirmOrderBean.TimeBean> mTimeList;
    private List<ConfirmOrderBean.CouponBean> mShoppingBagList;
    private List<ConfirmOrderBean.CouponBean> mCouponList;

    private String addressID;
    private String timeID;
    private String shoppingBagID;
    private String couponID;
    private String integral;
    private String shoppingCarID = ""; //购物车id
    private String totalMoney;  //小计金额
    private String finalMoney; //预付款


    /**
     * @param context
     * @param type    0  取货  1 送货上门
     * @param list
     */
    public static void start(Context context, int type, String money, List<CartGoodsBean> list) {
        Intent intent = new Intent(context, ConfirmOrderActivity.class);
        intent.putExtra(EXTRA_TYPE, type);
        intent.putExtra(EXTRA_MONEY, money);
        intent.putExtra(EXTRA_CONTENT, new Gson().toJson(list));
        context.startActivity(intent);
    }

    @Override
    protected int setContentLayoutRes() {
        return R.layout.activity_confirm_order;
    }

    @SuppressLint("DefaultLocale")
    @Override
    protected void initView() {

        Intent intent = getIntent();
        if (intent != null) {
            type = intent.getIntExtra(EXTRA_TYPE, 0);
            money = intent.getStringExtra(EXTRA_MONEY);
            String content = intent.getStringExtra(EXTRA_CONTENT);
            mList = new Gson().fromJson(content, new TypeToken<List<CartGoodsBean>>() {
            }.getType());
        }

        mTvTitleLeft.setEnabled(type == 0);
        mTvTitleRight.setEnabled(type == 1);
        mTvAddressUpdate.setVisibility(type == 1 ? View.VISIBLE : View.GONE);
        if (type == 0) {  //0  取货  1 送货上门
            mTvAddress.setText("取货地址");
            mTvDate.setText("预约取货日期");
            mTvTime.setText("预约取货时间");
        } else {
            mTvAddress.setText("送货地址");
            mTvDate.setText("预约送货日期");
            mTvTime.setText("预约送货时间");
        }

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        mRecyclerView.setAdapter(new OrderGoodsAdapter(R.layout.item_confirm_order, mList));

        mTvGoodsNum.setText(String.format("共%d件商品", mList.size()));
        mTvTotalMoney.setText(String.format("￥%s", money));
        mTvFinalMoney.setText(String.format("￥%s", money));

        totalMoney = money;

        for (CartGoodsBean cartGoodsBean : mList) {
            for (CartGoodsBean.SkuMapBean skuMapBean : cartGoodsBean.getSkuMap()) {
                shoppingCarID += skuMapBean.getMscId() + ",";
            }
        }

        shoppingCarID = shoppingCarID.substring(0, shoppingCarID.length() - 1);
        LogUtil.e("购物车id : " + shoppingCarID);

        mCbIntegral.setOnCheckedChangeListener(this);
    }

    List<Map<String, Object>> skuList = new ArrayList<>();

    @Override
    protected void initData() {
        for (CartGoodsBean cartGoodsBean : mList) {
            for (CartGoodsBean.SkuMapBean skuMapBean : cartGoodsBean.getSkuMap()) {
                Map<String, Object> map = new HashMap<>();
                map.put("skuId", skuMapBean.getSkuId());
                map.put("quantity", skuMapBean.getMscQuantity());
                skuList.add(map);
            }
        }
        mPresenter.getOrderData(type + 1, skuList);
    }

    private static final int CHOOSE_ADDRESS_CODE = 0x111;

    @OnClick(R.id.tv_address_update)
    void updateAddress() {
        AddressActivity.startForResult(this, true, CHOOSE_ADDRESS_CODE);
    }

    /**
     * 选择取货送货时间
     */
    @OnClick(R.id.ll_time)
    void getTimeList() {
        new OrderTimeChooseDialog.Builder(this).setList(mTimeList).setOnItemClickListener((dialog, position) -> {
            mTvTime2.setText(mTimeList.get(position).getName());
            timeID = mTimeList.get(position).getID();
            dialog.dismiss();
        }).build().show();
    }


    /**
     * 选择购物袋
     */
    @OnClick(R.id.ll_shopping_bag)
    void getShoppingBagList() {

        new OrderCouponChooseDialog.Builder(this).setList(mShoppingBagList).setOnItemClickListener((dialog, position) -> {
            mTvShoppingBag.setText(mShoppingBagList.get(position).getName() + mShoppingBagList.get(position).getMoney());
            shoppingBagID = mShoppingBagList.get(position).getID();
            mPresenter.calculateMoney(shoppingBagID, couponID, mCbIntegral.isChecked() ? integralVal : "0", skuList);
            dialog.dismiss();
        }).build().show();
    }

    /**
     * 选择优惠券
     */
    @OnClick(R.id.ll_coupon)
    void getCouponList() {
        new OrderCouponChooseDialog.Builder(this).setList(mCouponList).setOnItemClickListener((dialog, position) -> {
            mTvCoupon.setText(mCouponList.get(position).getName() + mCouponList.get(position).getMoney());
            couponID = mCouponList.get(position).getID();
            mPresenter.calculateMoney(shoppingBagID, couponID, mCbIntegral.isChecked() ? integralVal : "0", skuList);
            dialog.dismiss();
        }).build().show();
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            mPresenter.calculateMoney(shoppingBagID, couponID, integralVal, skuList);
        } else
            mPresenter.calculateMoney(shoppingBagID, couponID, "0", skuList);
    }

    /**
     * 提交订单
     */
    @OnClick(R.id.tv_commit_order)
    void commitOrder() {
        if (TextUtils.isEmpty(addressID)) {
            ToastHelper.getInstance(this).showWarn("请选择地址");
            return;
        }

        if (TextUtils.isEmpty(timeID)) {
            ToastHelper.getInstance(this).showWarn("请选择时间");
            return;
        }
        if (TextUtils.isEmpty(shoppingBagID)) {
            ToastHelper.getInstance(this).showWarn("请选择购物袋");
            return;
        }
        if (TextUtils.isEmpty(couponID)) {
            ToastHelper.getInstance(this).showWarn("请选择优惠券");
            return;
        }
        String remark = mEdtRemark.getText().toString();
        /*if (TextUtils.isEmpty(remark)) {
            ToastHelper.getInstance(this).showWarn("请输入备注信息");
            return;
        }*/
        mPresenter.createOrder(type + 1, addressID, timeID, shoppingBagID, couponID, mCbIntegral.isChecked() ? integral : "0", shoppingCarID, remark, totalMoney, finalMoney);
    }


    @Override
    protected ConfirmOrderPresenter createPresenter() {
        return new ConfirmOrderPresenter();
    }

    @Override
    public void showLoadingView() {
        showLoadingDialog();
    }

    @Override
    public void hideLoadingView() {
        hideLoadingDialog();
    }

    @Override
    public void onNetworkError() {
        hideLoadingDialog();
    }

    @Override
    public void showOrderData(ConfirmOrderBean bean) {

        ConfirmOrderBean.AddressBean addressBean = bean.getAddress();
        if (addressBean != null) {
            mTvNoAddress.setVisibility(View.GONE);
            mTvStoreName.setText(addressBean.getName());
            mTvStoreAddress.setText(addressBean.getAddress());
            mTvStoreTel.setText(addressBean.getMobile());
        } else {
            mTvNoAddress.setVisibility(View.VISIBLE);
        }
        mTvDate2.setText(bean.getDate());
        ConfirmOrderBean.IntegralBean integralBean = bean.getIntegral();
        mTvIntegral.setText(integralBean.getName());
        integralVal = integralBean.getValue();

        mTimeList = bean.getTime();
        mShoppingBagList = bean.getShoppingBag();
        mCouponList = bean.getCoupon();

        mTvFinalMoney.setText(String.format("￥%s", bean.getAdvancePayment()));


        if (type == 0)
            addressID = UserManager.getInstance().getStoreId();
        else if (addressBean != null) {
            addressID = addressBean.getID();
        }

        integral = integralBean.getValue();
        finalMoney = bean.getAdvancePayment();
    }

    @Override
    public void onRequestFailed(String message) {
        ToastHelper.getInstance(this).showWarn(message);
    }

    @Override
    public void showCreateOrderRes(HttpRespond<String> respond) {
        ToastHelper.getInstance(this).showSucceed(respond.message);
        ChoosePayTypeActivity.start(this, respond.data);
        finish();
    }

    @Override
    public void showCalculateRes(String data) {
        mTvFinalMoney.setText(String.format("￥%s", data));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            AddressBean bean = (AddressBean) data.getSerializableExtra("data");
            mTvStoreName.setText(bean.name);
            mTvStoreAddress.setText(bean.address);
            mTvStoreTel.setText(bean.mobile);
            addressID = bean.addressId;
            mTvNoAddress.setVisibility(View.GONE);
        }
    }


    class OrderGoodsAdapter extends BaseQuickAdapter<CartGoodsBean, BaseViewHolder> {

        public OrderGoodsAdapter(int layoutResId, @Nullable List<CartGoodsBean> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, CartGoodsBean item) {

            ImageView iv = helper.getView(R.id.item_pic);
            helper.setVisible(R.id.item_isNew, item.getIsNew() == 1);
            ImageUtils.showImage(ConfirmOrderActivity.this, item.getDeputyPic(), iv);
            helper.setText(R.id.item_title, item.getComName());

            RecyclerView recyclerView = helper.getView(R.id.rv_spec);
            recyclerView.setLayoutManager(new LinearLayoutManager(ConfirmOrderActivity.this));
            recyclerView.setAdapter(new OrderGoodsSubAdapter(R.layout.item_confirm_order_sub, item.getSkuMap()));
        }
    }

    class OrderGoodsSubAdapter extends BaseQuickAdapter<CartGoodsBean.SkuMapBean, BaseViewHolder> {

        public OrderGoodsSubAdapter(int layoutResId, @Nullable List<CartGoodsBean.SkuMapBean> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, CartGoodsBean.SkuMapBean item) {
            helper.setText(R.id.item_price, String.format("￥%s", item.getPrice()));
            helper.setText(R.id.item_specification, String.format("(%s%s/%s)", item.getSpQuantity(), item.getComUnitName(), item.getSkuUnitName()));
            helper.setText(R.id.item_unit_price, String.format("每%s￥%s元", item.getComUnitName(), item.getUnitPrice()));
            helper.setText(R.id.item_num, "x" + item.getMscQuantity());
        }
    }
}
